﻿using System;
using System.Linq;
using System.Windows;
using Caliburn.Micro;
using Microsoft.Win32;

namespace SunXmlEditor
{
  public partial class ShellView : Window
    , IHandle<ErrorMessage>
    , IHandle<OpenCommandMessage>
    , IHandle<FileReloadedMessage>
  {
    public ShellView()
    {
      InitializeComponent();
    }

    private readonly IEventAggregator _EventAggregator = IoC.Get<IEventAggregator>();

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
      _EventAggregator.Subscribe(this);
    }

    private void Window_Unloaded(object sender, RoutedEventArgs e)
    {
      _EventAggregator.Unsubscribe(this);
    }

    private void Window_Drop(object sender, DragEventArgs e)
    {
      try
      {
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
        {
          string[] files = e.Data.GetData(DataFormats.FileDrop, false) as string[];
          // open files[0];
          var file0 = files?.FirstOrDefault();
          if (null != file0)
          {
            _EventAggregator.PublishOnUIThread(new OpenXmlFileMessage(file0));
          }
        }
      }
      catch (Exception ex)
      {
        _EventAggregator.PublishOnUIThread(new ErrorMessage(ex, "打开文件异常。"));
      }
    }

    private void CollapseAll_Click(object sender, RoutedEventArgs e)
    {
      RootSunXElement_TreeView.CollapseAll();
    }

    private void ExpandAll_Click(object sender, RoutedEventArgs e)
    {
      RootSunXElement_TreeView.ExpandAll();
    }

    #region 热键命令事件

    private void Save_Command_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
    {
      _EventAggregator.PublishOnUIThread(new SaveCommandMessage());
    }

    private void Open_Command_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
    {
      _EventAggregator.PublishOnUIThread(new OpenCommandMessage());
    }

    #endregion 热键命令事件

    #region IHandle

    public void Handle(ErrorMessage message)
    {
      MessageBox.Show(this, message.Exception.Message, message.Message);
    }

    public void Handle(OpenCommandMessage message)
    {
      var dialog = new OpenFileDialog()
      {
        Multiselect = false
      };
      if (true == dialog.ShowDialog())
      {
        _EventAggregator.PublishOnUIThread(new OpenXmlFileMessage(dialog.FileName));
      }
    }

    public void Handle(FileReloadedMessage message)
    {
      RootSunXElement_TreeView.ExpandTree(1);
    }

    #endregion IHandle
  }
}